﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;
using Telerik.Web.UI;
using System.Data.Common;
using System.Data;
using System.Web.Services;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    private Cache cache = HttpContext.Current.Cache;
    Control mainControl;
    DatabaseHelper DB = new DatabaseHelper();
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
         LoadNavigate();
    }
    private void LoadNavigate()
    {

        if (Page.RouteData.Values["FunctionName"] != null && Session["isLogin"] != null)
        {
            DBDataContext db = new DBDataContext();
            string funcName = Page.RouteData.Values["FunctionName"].ToString();


            Function f = db.Functions.FirstOrDefault(x => x.MethodName == funcName);
            int id = 0;
            if (f != null)
            {
                id = f.ID;
            }

            var t = db.Function_GetAllParent(id);
            StringBuilder sb = new StringBuilder();
            sb.Append("<li><span class='glyphicon glyphicon-play'></span><a href='" + ResolveUrl("~/Default.aspx") + "'>Trang chủ</a></li>");
            foreach (var item in t)
            {
                sb.Append("<li><a href='" + item.MethodName + "'>  " + item.FunctionName + " </a></li>");
            }
            uiNavigate.InnerHtml = sb.ToString();
        }
        else
        {
            uiNavigate.Visible = false;
        }



    }
    protected void Page_Init(object sender, EventArgs e)
    {

        string funcName = string.Empty;
        string param = string.Empty;
        string username = string.Empty;

        if (Page.RouteData.Values["FunctionName"] != null)
        {
            funcName = Page.RouteData.Values["FunctionName"].ToString();

            Session["lastFunctionName"] = funcName;
        }
        else
        {
            funcName = "default.aspx";
        }


        if (Page.RouteData.Values["Param"] != null)
        {
            param = Page.RouteData.Values["Param"].ToString();
            Session["Param"] = param;
        }

        if (Session["isLogin"] == null)
        {
            funcName = "login";
            /*
            if (Session["lastFunctionName"] ==null || Session["lastFunctionName"].ToString().Length==0)
            {
                funcName = "login";
            }
            else
            {
                //Load popup login
                funcName = "login";
                //JavascriptUtil.LoadScript(Page, "<script>$('.popup-login').show()</script>");
            }
             */
        }

        //neu chua doi pass thi chuyen sang url doi pass
        if (Session["isChangePass"] != null && Session["isChangePass"].ToString() == "no")
        {
            funcName = "ChangePassword";
        }
        /*
        if (Session["isLogin"] != null && Session["isChangePass"] == null)
        {
            username = Session["UserName"].ToString();
            if (Request.Browser.IsMobileDevice)
            {
                funcName = funcName.Split('/')[0];
            }
            bool hasAuthorization = AuthorizationUtil.HasAuthorizationForm(username, funcName);
            if (!hasAuthorization)
            {
                JavascriptUtil.LoadMessage(Page, false, "User: " + Session["UserName"].ToString() + " chưa được phân quyền cho chức năng");
                funcName = "default.aspx";
                uiNavigate.Visible = false;
            }
        }
        */

        DBDataContext dtx = LINQUtil.GetDBReadOnly();
        var function = (from f in dtx.Functions
                        where f.MethodName == funcName
                        select f).FirstOrDefault();

        if (function != null)
        {
            string url = ResolveUrl(function.WebScreen);
            if (funcName.ToLower() != "login" && funcName.ToLower() != "changepassword")
            {
                // Kiểm tra UserName này có được phân quyền tương ứng với màn hình muốn truy cập. Tránh copy/past/tự ý type Url khi không được phân quyền trên menu.
                DB.ClearParameter();
                DbParameter paramParentID = DB.Parameter;
                paramParentID.ParameterName = "UserName";
                paramParentID.DbType = DbType.String;
                paramParentID.Value = Session["UserName"];

                DbParameter paramUserID = DB.Parameter;
                paramUserID.ParameterName = "MethodName";
                paramUserID.DbType = DbType.String;
                paramUserID.Value = Utils.KillChars(funcName);

                DB.AddParameter(paramParentID);
                DB.AddParameter(paramUserID);

                dt = DB.ExecuteDataTable("UserRole_CheckId", CommandType.StoredProcedure, ConnectionState.CloseOnExit);

                if (dt.Rows[0]["Result"].ToString() == "F") // honglk fix lại
                {
                    mainControl = LoadControl("~/Admin/Components/Error.ascx");
                    phContent.Controls.Add(mainControl);
                    Session["ErrorMessage"] = "Bạn không có quyền truy cập trang này!";
                    return;
                }
            }

            mainControl = LoadControl(url);
            phContent.Controls.Add(mainControl);
            Page.Title = function.FunctionName;
            //AuthorizationUtil.AuthorizationForm(mainControl, username, funcName);
        }
        else
        {
            mainControl = LoadControl("~/Admin/Components/Home.ascx");
            phContent.Controls.Add(mainControl);
            //Page.Title = function.FunctionName;
        }
    }

    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                string cookieHeader = Request.Headers["Cookie"];

                if (!String.IsNullOrEmpty(cookieHeader) && cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
                {
                    Response.Redirect("~/Default.aspx", true);

                }

            }

        }
    }
}